package com.dxysun.springboot.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.dxysun.springboot.view.MyMappingJackson2JsonView;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

/**
 * 通用的业务异常处理器，防止异常直接抛到前台用户中，统一按照app/sdk协议进行包装错误信息和记录错误日志
 * @author hzwumsh
 * 创建时间 2020-09-10 13:48
 *
 */
@Configuration
public class CommonHandlerExceptionResolver implements HandlerExceptionResolver, Ordered
{

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex)
	{
		//ignore client abort exception
		ex.printStackTrace();
		return createResponse(ex);
	}



	private ModelAndView createResponse(Exception ex)
	{

		ModelAndView modelAndView = new ModelAndView();
		MyMappingJackson2JsonView view = new MyMappingJackson2JsonView();
		view.setExtractValueFromSingleKeyModel(true);
		modelAndView.setView(view);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("error", ex.getMessage());
		modelAndView.addObject("result", jsonObject);
		return modelAndView;
	}


	@Override
	public int getOrder()
	{
		return Ordered.HIGHEST_PRECEDENCE;
	}
}
